package com.bpmn.flow.cmd;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.HistoryService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.identitylink.service.HistoricIdentityLinkService;
import org.flowable.identitylink.service.impl.persistence.entity.HistoricIdentityLinkEntity;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntity;
import org.flowable.task.api.history.HistoricTaskInstance;

import java.util.List;

/**
 * @author rain
 * @description 任务抄送Command类
 * @date 2025年04月18日 16:34
 */
@AllArgsConstructor
public class TaskCarbonCopyCmd implements Command<Void> {

    private String taskId;

    private List<String> userIds;

    private static final String TYPE = "carbonCopy";

    @Override
    public Void execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        HistoryService historyService = processEngineConfiguration.getHistoryService();
        //校验并获取任务实例
        HistoricTaskInstance historicTaskInstance = checkAndGetHistoricTaskInstance(historyService);
        if (historicTaskInstance.getEndTime() == null) {
            //对于未结束的任务同时创建运行时和历史关联关系
            for (String userId : userIds) {
                IdentityLinkEntity identityLink = processEngineConfiguration.getIdentityLinkServiceConfiguration()
                        .getIdentityLinkService()
                        .createTaskIdentityLink(taskId, userId, null, TYPE);
                CommandContextUtil.getHistoryManager().recordIdentityLinkCreated(identityLink);
            }
        } else {
            //对于已结束的任务，仅创建历史关联关系
            HistoricIdentityLinkService historicIdentityLinkService = processEngineConfiguration.getIdentityLinkServiceConfiguration()
                    .getHistoricIdentityLinkService();
            for (String userId : userIds) {
                HistoricIdentityLinkEntity historicIdentityLink = historicIdentityLinkService.createHistoricIdentityLink();
                historicIdentityLink.setGroupId(null);
                historicIdentityLink.setProcessInstanceId(null);
                historicIdentityLink.setTaskId(taskId);
                historicIdentityLink.setType(TYPE);
                historicIdentityLink.setUserId(userId);
                historicIdentityLinkService.insertHistoricIdentityLink(historicIdentityLink, false);
            }
        }
        return null;
    }

    /**
     * 校验并获取任务实例
     */
    private HistoricTaskInstance checkAndGetHistoricTaskInstance(HistoryService historyService) {
        if (StrUtil.isBlank(taskId)) {
            throw new FlowableIllegalArgumentException("taskId不能为空!");
        }
        if (CollUtil.isEmpty(userIds)) {
            throw new FlowableIllegalArgumentException("userIds不能为空!");
        }
        HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        if (historicTaskInstance == null) {
            throw new FlowableException("id为" + taskId + "的任务实例不存在");
        }
        return historicTaskInstance;
    }
}
